package libx

import (
	"net/http"
)

const (
	KEY_CODE = "code"
	KEY_INFO = "info"
	KEY_DATA = "data"

	ErrCodeDBUnknown      = 700000
	ErrCodeDBRecordExists = 700001
	ErrCodeDBRecordCreate = 700002
	ErrCodeDBRecordNone   = 700003

	ErrCodeParam = 600000

	ErrCodeSrvUnknown = 500000
	ErrCodeSrvEncode  = 500001

	ErrCodeNoToken        = 401000
	ErrCodeDenied         = 401001
	ErrCodeTokenFail      = 401002
	ErrCodeNoSecret       = 401003
	ErrCodeInvalidRequest = 401004
)

type GinContext interface {
	JSON(code int, obj any)
}

func Success(ctx GinContext, info string, data any) {
	ctx.JSON(http.StatusOK, ResM(http.StatusOK, info, data))
}

func Failure(ctx GinContext, code int, info string) {
	ctx.JSON(http.StatusOK, ResM(code, info, nil))
}

func ResM(code int, info string, data any) map[string]any {
	m := map[string]any{
		KEY_CODE: code,
	}
	if len(info) > 0 {
		m[KEY_INFO] = info
	} else {
		m[KEY_INFO] = http.StatusText(code)
	}
	if data != nil {
		m[KEY_DATA] = data
	}
	return m
}
